#-*- coding:utf-8 -*-
import os
import sys
import json
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from widgets.maya_project_control import GlobalControl
from MM import *
from MOD import *
from RIG import *
from ANI import *
from ENV import *
from LGT import *
try:
    reload(sys)
    sys.setdefaultencoding('utf-8')
    import maya.cmds as cmds
    from maya import OpenMayaUI as omui
    from shiboken2 import wrapInstance
except Exception as import_err:
    print('test')


class FrameTemplate(QFrame):
    """
    create script btns
    only 5 btns per Frame
    """
    def __init__(self,script_dir,script_list):
        super(FrameTemplate, self).__init__()
        
        self.script_dir = script_dir  # eg:xxx/ENV 
        self.script_list = script_list  #['']
        self.btn_style = '''QToolButton{color:black}
                                      QToolButton:hover{color:red}
                                      QToolButton{background-color:#CCCCCC}
                                      QToolButton{border:2px}
                                      QToolButton{border-radius:6px}
                                      QToolButton{padding:2px 1px}
                                      QToolButton{text-align:bottom }
                                      QToolButton{font-size:12px}'''
        self.main_layout = QHBoxLayout()
        self.init_btns(script_list)
        self.setLayout(self.main_layout)

    def init_btns(self,script_list):
        """

        :param script_config: [config,config,...,] ,already sorted by keys before init_btns
                    lenth(script_config) <=5
                    config : {'name':xxx,'icon':name,'script':xxx_path,...,'pipeline':xxx}
                             pipeline: MM,ENV,ANI,...
        :return:
        """
        if script_list:
            no_icon = os.path.join(os.path.dirname(__file__),'imgs','no.png')
            
            for script in script_list:
                
                icon_path = os.path.join(self.script_dir,'icons',script+'.png')
                icon_path = icon_path if os.path.exists(icon_path) else no_icon
                script_info = eval('{}._doc()'.format(script))
                name = script_info.get('name','')
                doc = script_info.get('doc','')
                btn = QToolButton()
                btn.setText(name)
                btn.setToolTip(script)
                btn.setIcon(QIcon(icon_path))
                btn.setIconSize(QSize(50, 50))
                btn.setStyleSheet(self.btn_style)
                btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
                btn.clicked.connect(self._exec_run)
                self.main_layout.addWidget(btn)

    def _exec_run(self):
        btn = self.sender()
        script = btn.toolTip()
        eval('{}._run()'.format(script))


class GridWidget(QWidget):

    def __init__(self,department,script_dir,parent=None):
        super(GridWidget, self).__init__(parent)
        self.department = department
        self.script_dir = script_dir
        self.main_layout = QVBoxLayout()
        self.main_layout.setAlignment(Qt.AlignTop)
        self.department_label = QLabel(department)
        self.department_label.setAlignment(Qt.AlignCenter)
        self.main_layout.addWidget(self.department_label)
        self.setLayout(self.main_layout)
        self.init_grid(self.script_dir)

    def init_grid(self,script_dir):
        """
        init department grid widget
        :param config_info:
        :return:
        """
        # icon_path = os.path.join(script_dir, 'icons')
        files = os.listdir(script_dir)
        scripts = []
        for f in files:
            if f.endswith('.py') and f!='__init__.py':
                scripts.append(os.path.splitext(f)[0])
        print('scripts:',scripts)
        script_list = self.clip_list(scripts,5)
        for s in script_list:
            btn_frame = FrameTemplate(self.script_dir,s)
            self.main_layout.addWidget(btn_frame)

        # for i in range(3):


    def clip_list(self,a,c):  #a为原列表，c为等分长度
        clip_back=[]
        if len(a)>c:
            for i in range(int(len(a) / c)):
                # print(i)
                clip_a = a[c * i:c * (i + 1)]
                clip_back.append(clip_a)
                # print(clip_a)
            # last 剩下的单独为一组
            last = a[int(len(a) / c) * c:]
            if last:
                clip_back.append(last)
        else:  #如果切分长度不小于原列表长度，那么直接返回原列表
            clip_back = [a]

        return clip_back


class HelpWidget(QWidget):

    def __init__(self,parent=None):
        super(HelpWidget, self).__init__(parent)
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(15)
        self.main_layout.setAlignment(Qt.AlignTop)
        self.doc_layout = QHBoxLayout()
        self.doc_label = QLabel(u'文档链接')
        self.doc_text = QTextBrowser()
        self.doc_text.setOpenExternalLinks(True)
        self.doc_text.setFixedHeight(200)
        self.init_doc()
        self.doc_layout.addWidget(self.doc_label)
        self.doc_layout.addWidget(self.doc_text)
        self.update_layout = QHBoxLayout()
        self.update_label = QLabel(u'更新记录')
        self.update_text = QTextBrowser()
        self.update_text.setFixedHeight(200)
        self.update_layout.addWidget(self.update_label)
        self.update_layout.addWidget(self.update_text)
        self.init_update()
        self.contributor_layout = QHBoxLayout()
        self.contributor_label = QLabel(u'贡献人员')
        self.contributor_text = QTextBrowser()
        self.contributor_text.setFixedHeight(200)
        self.contributor_layout.addWidget(self.contributor_label)
        self.contributor_layout.addWidget(self.contributor_text)
        self.init_contributor()
        self.logo_label = QLabel()
        self.logo_label.setAlignment(Qt.AlignCenter)
        logo_path = os.path.join(parent.img_path,'timeaxis.png')
        self.logo_label.setPixmap(QPixmap(logo_path))
        self.main_layout.addLayout(self.doc_layout)
        self.main_layout.addLayout(self.update_layout)
        self.main_layout.addLayout(self.contributor_layout)
        self.main_layout.addWidget(self.logo_label)
        self.setLayout(self.main_layout)

    def init_doc(self):
        text = " 使用帮助 : <body> <bodylink='#7bea89' alink='#7bea89' vlink ='#7bea89'>  <a href = 'http://192.168.1.83:8090/pages/viewpage.action?pageId=28082276' bodylink='#7bea89' > wiki </a> </body> "
        self.doc_text.setText(text)

    def init_update(self):
        text = '''开发过程：
        2021-08-11 : 修改创建目录
        2021-08-13 : 拍屏与主相机
        2021-08-18 : 各阶段界面检查
        2021-08-20 : 1.提交文件OK 下一个触发cgtw信息 2.测试动画提交
        2021-08-24 : 跟踪，动画，绑定三个阶段检测面板初版
        2021-08-26 : 添加ma配置
        2021-08-27 : 导出FBX 导出ABC
        2021-08-30 : 提交FBX
        2021-09-09 : 模型检查
        2021-09-13 : 模型提交单帧
        2021-09-17 : 增加灯光提交
        2021-09-22 : 场景路径，sourceimage
        2021-09-25 : 可下载原始shot
        2021-09-27 : 添加doc
        '''
        self.update_text.setText(text)

    def init_contributor(self):
        text = '''开发阶段一
周期：2021/03/22-2021/09/30， 从0到Timeaxis_Tools v1.0
开发目标：规范maya制作环节的本地文件管理，统一视频审核文件规格，提交文件进行技术检查，汇总各部门的效率工具
需求文档：何鑫泉，谭伟健，韩超，陈杰，黄亚楠，马福明，庞浩熙，李伟
程序：张洲
帮助文档：张洲
版本测试：王英，黄旭，马福明，何鑫泉
        '''
        self.contributor_text.setText(text)

class TestGridWidget(QWidget):

    def __init__(self,department):
        super(TestGridWidget, self).__init__()
        self.label_font = QFont('',15,65)
        self.main_layout = QVBoxLayout()
        self.main_layout.setAlignment(Qt.AlignTop)
        self.department_label = QLabel(department)
        self.department_label.setAlignment(Qt.AlignCenter)
        self.department_label.setFont(self.label_font)

        self.main_layout.addWidget(self.department_label)
        self.init_grid()
        self.setLayout(self.main_layout)

    def init_grid(self):

        for i in range(3):
            btn_frame = FrameTemplate([1,2,3,4,5])
            self.main_layout.addWidget(btn_frame)

class MayaTool(QWidget):

    def __init__(self,parent=None):
        super(MayaTool, self).__init__(parent)

        self.setWindowFlags(Qt.WindowStaysOnTopHint|Qt.Window)
        self.img_path = os.path.join(os.path.dirname(__file__),'imgs')
        project_icon = os.path.join(self.img_path,'timelogo.png')
        self.btn_style = '''QToolButton{color:black}
                                      QToolButton:hover{color:red}
                                      QToolButton{background-color:#CCCCCC}
                                      QToolButton{border:2px}
                                      QToolButton{border-radius:6px}
                                      QToolButton{padding:5px 5px}
                                      QToolButton{text-align:bottom }
                                      QToolButton{font-size:12px}'''
        self.btn_font = QFont('',12,65)

        self.pwd = os.path.dirname(__file__)
        self.MM = os.path.join(self.pwd,'MM')
        self.MOD = os.path.join(self.pwd,'MOD')
        self.RIG = os.path.join(self.pwd,'RIG')
        self.ANI = os.path.join(self.pwd,'ANI')
        self.ENV = os.path.join(self.pwd,'ENV')
        self.LGT = os.path.join(self.pwd,'LGT')


        self.project_window = None
        self.mm_window = None
        self.mod_window = None
        self.ani_window = None
        self.rig_window = None
        self.env_window = None
        self.lgt_window = None
        self.help_window = None
        self.current_window = None

        self.setWindowTitle(u'TimeVFX Tools V1.0')
        window_icon=QIcon()
        window_icon.addPixmap(QPixmap(project_icon))
        self.setWindowIcon(window_icon)
        self.main_layout = QVBoxLayout()
        self.department_layout = QHBoxLayout()
        self.project_btn = QToolButton(self)
        self.project_btn.setText(u'项目')
        self.project_btn.setFont(self.btn_font)
        img_project = os.path.join(self.img_path,'project.png')
        self.project_btn.setIcon(QIcon(img_project))
        self.project_btn.setIconSize(QSize(30, 30))
        self.project_btn.setStyleSheet(self.btn_style)
        self.project_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.project_btn.clicked.connect(self._change_project)
        self.mm_btn = QToolButton()
        self.mm_btn.setText(u'跟踪')
        self.mm_btn.setFont(self.btn_font)
        img_mm = os.path.join(self.img_path,'mm.png')
        self.mm_btn.setIcon(QIcon(img_mm))
        self.mm_btn.setIconSize(QSize(30, 30))
        self.mm_btn.setStyleSheet(self.btn_style)
        self.mm_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.mm_btn.clicked.connect(self._change_mm)
        img_mod = os.path.join(self.img_path, 'mod.png')
        self.mod_btn = QToolButton()
        self.mod_btn.setText(u'模型')
        self.mod_btn.setFont(self.btn_font)
        self.mod_btn.setIcon(QIcon(img_mod))
        self.mod_btn.setIconSize(QSize(30, 30))
        self.mod_btn.setStyleSheet(self.btn_style)
        self.mod_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.mod_btn.clicked.connect(self._change_mod)
        img_ani = os.path.join(self.img_path, 'ani.png')
        self.ani_btn = QToolButton()
        self.ani_btn.setText(u'动画')
        self.ani_btn.setFont(self.btn_font)
        self.ani_btn.setIcon(QIcon(img_ani))
        self.ani_btn.setIconSize(QSize(30, 30))
        self.ani_btn.setStyleSheet(self.btn_style)
        self.ani_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.ani_btn.clicked.connect(self._change_ani)
        img_rig = os.path.join(self.img_path, 'rig.png')
        self.rig_btn = QToolButton()
        self.rig_btn.setText(u'绑定')
        self.rig_btn.setFont(self.btn_font)
        self.rig_btn.setIcon(QIcon(img_rig))
        self.rig_btn.setIconSize(QSize(30, 30))
        self.rig_btn.setStyleSheet(self.btn_style)
        self.rig_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.rig_btn.clicked.connect(self._change_rig)
        img_env = os.path.join(self.img_path, 'env.png')
        self.env_btn = QToolButton()
        self.env_btn.setText(u'场景')
        self.env_btn.setFont(self.btn_font)
        self.env_btn.setIcon(QIcon(img_env))
        self.env_btn.setIconSize(QSize(30, 30))
        self.env_btn.setStyleSheet(self.btn_style)
        self.env_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.env_btn.clicked.connect(self._change_env)
        img_light = os.path.join(self.img_path, 'light.png')
        self.light_btn = QToolButton()
        self.light_btn.setText(u'灯光')
        self.light_btn.setFont(self.btn_font)
        self.light_btn.setIcon(QIcon(img_light))
        self.light_btn.setIconSize(QSize(30, 30))
        self.light_btn.setStyleSheet(self.btn_style)
        self.light_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.light_btn.clicked.connect(self._change_lgt)
        help_img = os.path.join(self.img_path,'help.png')
        self.help_btn = QToolButton()
        self.help_btn.setText(u'帮助')
        self.help_btn.setFont(self.btn_font)
        self.help_btn.setIcon(QIcon(help_img))
        self.help_btn.setIconSize(QSize(30, 30))
        self.help_btn.setStyleSheet(self.btn_style)
        self.help_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.help_btn.clicked.connect(self._change_help)
        self.department_layout.addWidget(self.project_btn)
        self.department_layout.addWidget(self.mm_btn)
        self.department_layout.addWidget(self.mod_btn)
        self.department_layout.addWidget(self.ani_btn)
        self.department_layout.addWidget(self.rig_btn)
        self.department_layout.addWidget(self.env_btn)
        self.department_layout.addWidget(self.light_btn)
        self.department_layout.addWidget(self.help_btn)

        self.project_window = QWidget()  #QFrame()
        self.tool_Layout = QVBoxLayout()
        self.project_control_window = GlobalControl()
        self.tool_Layout.addWidget(self.project_control_window)
        self.project_window.setLayout(self.tool_Layout)

        self.main_layout.addLayout(self.department_layout)
        self.main_layout.addWidget(self.project_window)
        self.setLayout(self.main_layout)

        self.last_window = self.project_window
        self.current_window = self.project_window
        self.move(1300, 0)
        # self.init_preset()

        self.init_ma_data()


    # def init_preset(self):
    #
    #     try:
    #         data = {}
    #         data['driver'] = cmds.getAttr('persp.driver')
    #         data['full_name'] = cmds.getAttr('persp.full_name')
    #         data['entity_name'] = cmds.getAttr('persp.entity_name')
    #         data['resolution'] = cmds.getAttr('persp.resolution')
    #         data['description'] = cmds.getAttr('persp.description')
    #         data['pipeline'] = cmds.getAttr('persp.pipeline')
    #         data['eps'] = cmds.getAttr('persp.eps')
    #         data['asset_shot'] = cmds.getAttr('persp.asset_shot')
    #         data['path'] = cmds.getAttr('persp.path')
    #         data['frame'] = cmds.getAttr('persp.frame')
    #         data['fps'] = cmds.getAttr('persp.fps')
    #         # data = json.dumps(data)
    #         self.project_control_window.init_preset(data)
    #
    #     except Exception as init_preset_ERR:
    #         print('init_preset_ERR:',str(init_preset_ERR))


    def get_ma_data(self):
        """
        尝试获取当前打开maya的配置信息
        :return:
        """
        ma_data = {}
        ma_path = cmds.file(q=True, sn=True)
        if ma_path:
            ma_fullname = os.path.split(ma_path)[1]
            ma_name = os.path.splitext(ma_fullname)[0]
            scence_dir = os.path.dirname(ma_path)

            ma_data_path = os.path.join(scence_dir, ma_name + '.cfg')
            if os.path.exists(ma_data_path):
                str_data = ''
                with open(ma_data_path, 'r') as r:
                    str_data = r.read()
                if str_data:
                    ma_data = eval(str_data)

        return ma_data

    def init_ma_data(self):
        try:
            ma_data = self.get_ma_data()
            print('ma_data:',ma_data)
            if ma_data:
                self.project_control_window.set_ma_data(ma_data)
        except Exception as init_ma_data:
            print('test')

    def _change_project(self):
        self.current_window.setHidden(True)
        self.current_window = self.project_window
        self.current_window.setHidden(False)
        self.main_layout.addWidget(self.current_window)
        if not self.project_control_window.ma_data:
            self.init_ma_data()


    def _change_mm(self):

        self.current_window.setHidden(True)
        self.mm_window = self.mm_window if self.mm_window else GridWidget(u'跟踪',self.MM,self)
        self.current_window = self.mm_window
        self.current_window.setHidden(False)
        self.main_layout.addWidget(self.current_window)

    def _change_mod(self):
        self.current_window.setHidden(True)
        self.mod_window = self.mod_window if self.mod_window else GridWidget(u'模型',self.MOD,self)
        self.current_window = self.mod_window
        self.current_window.setHidden(False)
        self.main_layout.addWidget(self.current_window)

    def _change_ani(self):
        self.current_window.setHidden(True)
        self.ani_window = self.ani_window if self.ani_window else GridWidget(u'动画',self.ANI,self)
        self.current_window = self.ani_window
        self.current_window.setHidden(False)
        self.main_layout.addWidget(self.current_window)

    def _change_rig(self):
        self.current_window.setHidden(True)
        self.rig_window = self.rig_window if self.rig_window else GridWidget(u'绑定',self.RIG,self)
        self.current_window = self.rig_window
        self.current_window.setHidden(False)
        self.main_layout.addWidget(self.current_window)

    def _change_env(self):
        self.current_window.setHidden(True)
        self.env_window = self.env_window if self.env_window else GridWidget(u'场景',self.ENV,self)
        self.current_window = self.env_window
        self.current_window.setHidden(False)
        self.main_layout.addWidget(self.current_window)

    def _change_lgt(self):
        self.current_window.setHidden(True)
        self.lgt_window = self.lgt_window if self.lgt_window else GridWidget(u'灯光',self.LGT,self)
        self.current_window = self.lgt_window
        self.current_window.setHidden(False)
        self.main_layout.addWidget(self.current_window)


    def _change_help(self):
        self.current_window.setHidden(True)
        self.help_window = self.help_window if self.help_window else HelpWidget(self)
        self.current_window = self.help_window
        self.current_window.setHidden(False)
        self.main_layout.addWidget(self.current_window)

    def closeEvent(self, *args, **kwargs):
        # print('close')
        self.setHidden(True)
        print('close')

def maya_main_window():
    '''
    Return the Maya main window widget as a Python object
    '''
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(main_window_ptr), QWidget)

def maya_tool():
    global dialog
    try:
        dialog.show()
        # dialog.setHidden(False)
        dialog.setHidden(False)
    except :

        dialog = MayaTool(parent=maya_main_window())
        dialog.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    m = MayaTool()

    # m = TestGridWidget()
    m.show()
    sys.exit(app.exec_())